//
//  LiveGoodsViewController.m
//  YouinRTCDemo
//
//  Created by super on 2021/11/12.
//

#import "LiveGoodsViewController.h"
#import <WebKit/WebKit.h>
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "TOCropViewController.h"
@interface LiveGoodsViewController ()<WKNavigationDelegate,WKScriptMessageHandler,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TOCropViewControllerDelegate,WKUIDelegate>
@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)UIView *bgView;///存放webview
@property(nonatomic,copy)NSString *token;
@property(nonatomic,assign)int timestamp;
@property(nonatomic,strong)NSMutableArray *imgArray;
@property (nonatomic,copy)NSString *file_url;
@end


@implementation LiveGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.file_url = @"";
    self.imgArray = [[NSMutableArray alloc] initWithCapacity:0];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [defaults dictionaryForKey:@"userInfo"];
    self.token = dict[@"token"];
    self.timestamp = [dict[@"exprise_time"] intValue];
    
    self.view.backgroundColor = [UIColor clearColor];
    UIView *bgView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:bgView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
    [bgView addGestureRecognizer:tap];
    [self createWebView];
}

- (void)createWebView
{
    self.bgView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT*0.7+30)];
    self.bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bgView];
    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

    // 根据需要去设置对应的属性
    _webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.7) configuration:config];
    _webView.navigationDelegate = self;
    _webView.configuration.preferences.javaScriptEnabled = true;
    _webView.UIDelegate = self;
    _webView.layer.cornerRadius = 10;
    _webView.layer.masksToBounds = YES;
    [self.bgView addSubview:_webView];
    self.webView.opaque = false;
    [self afn];

}

-(void)afn
{
    //1.创建网络状态监测管理者
    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
    [manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
//                NSLog(@"未知");
                break;
            case AFNetworkReachabilityStatusNotReachable:
//                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
//                NSLog(@"3G|4G");
                [self reloadWb];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
//                NSLog(@"WiFi");
                [self reloadWb];

                break;
            default:
                break;
        }
    }];
    [manger startMonitoring];
}


- (void)reloadGoodsListWithEnterpriseId:(NSString *)enterpriseId withLiveId:(NSString *)liveId
{
    self.enterpriseId = enterpriseId;
    self.liveId = liveId;
    [self reloadWb];
}

- (void)reloadWb{
    // 将时间戳转换为NSDate对象
    NSDate *exprise_date = [NSDate dateWithTimeIntervalSince1970:self.timestamp];
    
    // 获取当前日期的NSDate对象
    NSDate *currentDate = [NSDate date];
    NSComparisonResult result = [exprise_date compare:currentDate];

     // 根据比较结果打印不同的信息
     if (result == NSOrderedAscending) {
         NSLog(@"%@ 早于 %@", exprise_date, currentDate);
         [[YouinRTCManager shardManager] removeToken];
         [(AppDelegate *)[UIApplication sharedApplication].delegate loginOutWindowHome];
     }else{
         
         NSString *str = [NSString stringWithFormat:@"%@enterprise_id=%@&liveid=%@&app=ios",mobileGoods,self.enterpriseId,self.liveId];
         NSMutableURLRequest *requset = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:str]];
         
         WKHTTPCookieStore *cookieStore = self.webView.configuration.websiteDataStore.httpCookieStore;
         NSMutableDictionary *properties = [NSMutableDictionary dictionary];
         [properties setObject:cookieName forKey:NSHTTPCookieName];
         [properties setObject:self.token forKey:NSHTTPCookieValue];
         [properties setObject:@"live.youinsh.com" forKey:NSHTTPCookieDomain];
         [properties setObject:@"live.youinsh.com" forKey:NSHTTPCookieOriginURL];
         [properties setObject:@"/" forKey:NSHTTPCookiePath];
         [properties setObject:@"0" forKey:NSHTTPCookieVersion];
         NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
         [cookieStore setCookie:cookie completionHandler:^{
             NSLog(@"21");
         }];
         
         [self.webView loadRequest:requset];
         
         //拍照 getPhoto、takePhoto
     //    //从相册选取
         [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"takePhoto"];
         [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"getPhoto"];
         // 业务逻辑
         [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"getPhoto"];
         [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"takePhoto"];
         
     }
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"takePhoto"]) {
           //拍照
        [self localPhotos];
    }
    if ([message.name isEqualToString:@"getPhoto"]) {
       //从相册选取
        [self takePhotos];
    }
   
}

#pragma mark TZImagePickerControllerDelegate
#pragma mark  -- 从相册中选择照片

-(void)localPhotos{
    UIImagePickerController *photo = [[UIImagePickerController alloc] init];
    photo.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    photo.delegate = self;
    photo.allowsEditing = YES;
    photo.view.backgroundColor=[UIColor whiteColor];
    photo.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:photo animated:YES completion:nil];
}

//拍照
- (void)takePhotos{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self.navigationController presentViewController:picker animated:YES completion:^{
            NSLog(@"OK");
        }];
    }
    else {
        NSLog(@"模拟其中无法打开照相机，请在真机中使用");
    }
}

// 相机
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    UIImage *smallimage;
    if (picker.allowsEditing == YES) {
        smallimage  = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    }else{
        smallimage  = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    }
    
    TOCropViewController *cropViewController = [[TOCropViewController alloc] initWithImage:smallimage];
    cropViewController.delegate = self;
    cropViewController.aspectRatioPreset = TOCropViewControllerAspectRatioPresetCustom;
    cropViewController.toolbar.rotateClockwiseButtonHidden = YES;
    cropViewController.toolbar.clampButtonHidden = YES;
    cropViewController.toolbar.rotateCounterclockwiseButtonHidden = YES;
    cropViewController.toolbar.resetButtonHidden = YES;
    cropViewController.aspectRatioLockEnabled = YES;
    cropViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:cropViewController animated:NO completion:nil];
}


- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle
{
    __weak typeof(self) weakSelf = self;
    [[YouinRTCManager shardManager] uploadFileToQiniu:image successBlock:^(id  _Nonnull json) {
       NSLog(@"json");
       if ([json[@"code"] intValue] == 200) {
           NSString *inputValue = [NSString stringWithFormat:@"updateGoodsImage('%@')",json[@"result"][@"file_url"]];
           dispatch_async(dispatch_get_main_queue(), ^{
               [weakSelf.webView evaluateJavaScript:inputValue completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                   if (error) {
                       NSLog(@"JS执行错误: %@", error);
                       // 可以尝试alert测试基础JS功能是否正常
                       [weakSelf.webView evaluateJavaScript:@"alert('test')" completionHandler:nil];
                   } else {
                       NSLog(@"JS执行成功，返回: %@", result);
                   }
               }];;
           });
         
       }
   } failure:^(NSError * _Nonnull error) {
       NSLog(@"error");
   }];
    [cropViewController dismissViewControllerAnimated:NO completion:nil];
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(WK_SWIFT_UI_ACTOR void (^)(BOOL))completionHandler
{
    NSLog(@"121221");
}
//页面加载完成时调用
//- (void)webView:(WKWebView *)webView didFinishNavigation:( WKNavigation *)navigation
//{
//    NSDictionary *dic = @{@"saas_pro_token":self.token};
//    if(dic){
//        // 注入token
//        NSString *token = [dic mj_JSONString];
//        NSString *method = [NSString stringWithFormat:@"ioswindowfn('%@')",token];
//        [self.webView evaluateJavaScript:method completionHandler:^(id _Nullable json, NSError * _Nullable error) {
//            NSLog(@"1111%@",error);
//        }];
//    }
//}

-(void)tap{
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.bgView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT*0.7+30);
    } completion:^(BOOL finished) {
        weakSelf.view.hidden = true;
    }];
}

-(void)show{
//    NSDictionary *dict = [[YouinRTCManager shardManager] readNSUserDefaults];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [defaults dictionaryForKey:@"userInfo"];
    NSString *method = [NSString stringWithFormat:@"ioswindowfn('%@')",dict[@"token"]];
    [self.webView evaluateJavaScript:method completionHandler:^(id _Nullable json, NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];
 // 刷新页面
    [self.webView reload];
    self.view.hidden = false;
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.bgView.frame = CGRectMake(0, SCREEN_HEIGHT-SCREEN_HEIGHT*0.7, SCREEN_WIDTH, SCREEN_HEIGHT*0.7+30);
    }];
}

@end

